package com.example.yiparkapplication.activity.index.activity.ConvenientPaymentActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.load.engine.Resource;
import com.example.yiparkapplication.R;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.entity.MonthCard;
import com.example.yiparkapplication.entity.SingleCarSQL;
import com.example.yiparkapplication.util.BaseActivity;
import com.example.yiparkapplication.util.Common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CarOrderNopayActivity extends BaseActivity implements View.OnClickListener {

    private Handler handler;
    private String mCarNumber;
    private String mSearchType;//0：未付款，1：已付款
    private int mPage;
    private LinearLayoutManager linearLayoutManager;
    private TextView unfinished;
    private TextView finished;
    private boolean isLoadingMore = false;
    private List<SingleCarSQL> singleCarSQLList;
    private int bottomItem = 0;
    private int lastVisibleItem = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_order_nopay_layout);
        handler = new Handler();
        Intent intent = getIntent();
        mCarNumber = intent.getStringExtra("carNumber");
        mSearchType = "0";
        mPage = 1;
        showCarOrderList(mCarNumber, mSearchType, mPage);
        linearLayoutManager = new LinearLayoutManager(this);

        unfinished = findViewById(R.id.id_single_car_unfinished);
        unfinished.setOnClickListener(this);

        finished = findViewById(R.id.id_single_car_finished);
        finished.setOnClickListener(this);

    }

    @Override
    public void onClick(View v){
        switch(v.getId()){
            case R.id.id_single_car_unfinished:
                unfinished.setTextColor(getResources().getColor(R.color.color_blue_61a4ff));
                finished.setTextColor(getResources().getColor(R.color.color_332333));
                mSearchType = "0";
                mPage = 1;
                singleCarSQLList = new ArrayList<SingleCarSQL>();
                showCarOrderList(mCarNumber, mSearchType, mPage);
                break;
            case R.id.id_single_car_finished:
                finished.setTextColor(getResources().getColor(R.color.color_blue_61a4ff));
                unfinished.setTextColor(getResources().getColor(R.color.color_332333));
                mSearchType = "2";
                mPage = 1;
                singleCarSQLList = new ArrayList<SingleCarSQL>();
                break;
        }
    }

    public void toCarOrderActivity(String singleCarID){
        Intent intent = new Intent(CarOrderNopayActivity.this, CarOrderActivity.class);
        intent.putExtra("singleCarID", singleCarID);
        startActivity(intent);
    }

    private void showCarOrderList(String carNumber, String searchType, int page){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_SINGLE_CAR + "?plate=" + carNumber + "&searchType=" + searchType + "&page=" + page)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONObject jsonObject = joOut.getJSONObject("object");
                    if (jsonObject == null){
                        new Thread(){
                            public void run(){
                                handler.post(runnableShowView);
                            }
                        }.start();
                        new Thread(){
                            public void run(){
                                handler.post(runnableUi);
                            }
                        }.start();
                    }else{
                        new Thread(){
                            public void run(){
                                handler.post(runnableCar);
                            }
                        }.start();

                        int pages = jsonObject.getIntValue("pages");
                        if (mPage < pages){
                            mPage++;
                            isLoadingMore = true;
                        }else{
                            isLoadingMore = false;
                        }
                        JSONArray ja = jsonObject.getJSONArray("records");
                        for (int i=0;i<ja.size();i++){
                            JSONObject joIn = ja.getJSONObject(i);
                            int singleCarType = joIn.getInteger("parkStatus");
                            String routeLocationName = joIn.getString("streetName");
                            Date singleCarEndTime = joIn.getDate("parkEndTime");
                            Date singleCarStartTime = joIn.getDate("parkStartTime");
                            Double singleCarPrice = joIn.getDouble("price");
                            Double singleCarPaid = joIn.getDouble("paidPrice");
                            String truckSpace = joIn.getString("parkSpace");
                            String licensePlate = joIn.getString("plate");
                            Long singleCarId = joIn.getLong("singleCarId");
                            Integer discountCardId = joIn.getInteger("discountCarId");
                            Integer prepaidCardId = joIn.getInteger("prepaidCarId");
                            Integer couponId = joIn.getInteger("couponId");
                            SingleCarSQL singleCarSQL = new SingleCarSQL();
                            singleCarSQL.setRouteLocationName(routeLocationName);
                            singleCarSQL.setRouteLocationName(routeLocationName);
                            singleCarSQL.setSingleCarStartTime(singleCarStartTime);
                            singleCarSQL.setSingleCarEndTime(singleCarEndTime);
                            singleCarSQL.setSingleCarPrice(singleCarPrice);
                            singleCarSQL.setSingleCarPaid(singleCarPaid);
                            singleCarSQL.setSingleCarTruckSpace(truckSpace);
                            singleCarSQL.setSingleCarLicensePlate(licensePlate);
                            singleCarSQL.setSingleCarId(singleCarId);
                            singleCarSQL.setSingleCarType(singleCarType);
                            singleCarSQL.setDiscountCardId(discountCardId);
                            singleCarSQL.setPrepaidCardId(prepaidCardId);
                            singleCarSQL.setCouponId(couponId);

                            singleCarSQLList.add(singleCarSQL);
                        }

                        new Thread(){
                            public void run(){
                                handler.post(runnableUi);
                            }
                        }.start();
                    }
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

    Runnable runnableShowView = new Runnable() {
        @Override
        public void run() {
            RelativeLayout nullImg = findViewById(R.id.id_data_null_tip);
            nullImg.setVisibility(View.VISIBLE);
        }
    };
    Runnable runnableCar = new Runnable(){
        @Override
        public void run(){
            RelativeLayout nullImg = findViewById(R.id.id_data_null_tip);
            nullImg.setVisibility(View.GONE);
        }
    };
    Runnable runnableUi = new Runnable(){
        @Override
        public void run() {
            adapter(singleCarSQLList);
        }
    };

    private void adapter(List<SingleCarSQL> singleCarSQL){
        RecyclerView vRecyclerView = findViewById(R.id.id_single_car_recyclerView);
        vRecyclerView.setLayoutManager(linearLayoutManager);
        CarOrderAdapter carOrderAdapter = new CarOrderAdapter(singleCarSQL, CarOrderNopayActivity.this);
        vRecyclerView.setAdapter(carOrderAdapter);

        vRecyclerView.scrollToPosition(bottomItem);

        // 实现上拉加载重要步骤，设置滑动监听器，RecyclerView自带的ScrollListener
        vRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener(){
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState){
                super.onScrollStateChanged(recyclerView, newState);
                if (isLoadingMore){
                    if (newState == RecyclerView.SCROLL_STATE_IDLE){
                        if (lastVisibleItem + 1 == carOrderAdapter.getItemCount()){
                            isLoadingMore = false;
                            bottomItem = lastVisibleItem;
                            showCarOrderList(mCarNumber, mSearchType, mPage);
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy){
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
            }
        });
    }


}
